<?php

/**
*  代码下载
*/

class Down{
	function Down($db){
		$this->oDB = $db;
	}
	
	/**
	*  添加下载文件
	*/
	function insert($data,$check=''){
		//重复效验
		if (is_array($check)){
			unset($k,$v);
			foreach ($check AS $k=>$v) {
				$w[] = "`$k`='$v'";
			}
			$ck = $this->oDB->rows("SELECT count(*) AS cnt FROM down_file WHERE ".implode(' AND ',$w));
			
			//如果存在则提示
			if ($ck[cnt]>=1){
				return false;
			}
		}
		
		return $this->oDB->insert("down_file",$data);
	}
	
	
	/**
	*  获得文件列表
	*/
	function getList($where='',$num=20){
		$sql = "SELECT * FROM down_file $where ORDER BY id DESC";
		return $this->oDB->limit($sql, $_GET['page'], $num);
	}
	
	
	/**
	*  获取详细信息
	*/
	function getInfo($id){
		return $this->oDB->rows("SELECT * FROM down_file WHERE id='$id'");
	}
	
	/**
	*  更新下载文件
	*/
	function update($data,$where){
		return $this->oDB->update("down_file",$data,$where);
	}
	
	
	/**
	*  更新下载文件
	*/
	function del($id,$filedir){
		//获得数据
		$info = $this->getInfo($id);
		//删除附件
		if (trim($info[attach])){
			@unlink($filedir.$info[attach]);
		}
		return $this->oDB->query("DELETE FROM down_file WHERE id='$id'");
	}
	
	
	
	/**
	*  获得下载数量
	*/
	function getNum($id){
		$num = $this->oDB->rows("SELECT nums FROM down_file WHERE id='$id'");
		return (int)$num['nums'];
	}
	
	/**
	*  统计更新下载量
	*/
	function cntNum($id){
		$num	= $this->getNum($id);
		$new_num= $num +1;
		//更新数据
		$this->oDB->update('down_file',array('nums'=>$new_num)," id='$id'");
		return $new_num;
	}
	
	/**
	*  获得下载文件
	*/
	function getFile($id){
		global $attach_dir;
		$info = $this->getInfo($id);
		if (is_array($info)){
			//文件后缀
			$file_ext	= strtolower(substr(strrchr($info['attach'], '.'), 1));
			
			//文件路径
			$files		= $attach_dir.'/down/'.$info['attach'];
			
			//检查文件是否存在
			if (file_exists($files)) {
				
				//下载计数
				$this->cntNum($id);
				
				//打开文件
				$file = fopen($files,"r");
					//输入文件标签
					header("Content-Type: text/html; charset=utf-8");
 					header('Date: '.gmdate('D, d M Y H:i:s', $info['dates']).' GMT');
					header('Last-Modified: '.gmdate('D, d M Y H:i:s', $info['dates']).' GMT');
					Header("Content-type: application/octet-stream");
					header ("Pragma: no-cache");
					Header("Accept-Length: ".filesize($files));
					Header("Content-Disposition: attachment; filename=" . $info['filename'].'.'.$file_ext);
				//输出文件内容
				echo fread($file,filesize($files));
				fclose($file); 
				exit;
			}
		}

	}
}

?>